// app.js
App({
  onLaunch() {
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;  
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
      }
    })

    wx.startLocationUpdate({
      success: () => {
        wx.onLocationChange((result) => {
          this.globalData.position_inited = true
          this.globalData.position.lat = result.latitude
          this.globalData.position.lng = result.longitude
        })
      }
    })

    // 登录
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    
    wx.checkSession({
      complete: () => {
        wx.hideLoading({
          success: (res) => {},
        })
      },
      success: () => {
        if(this.globalData.access_token == null || this.globalData.access_token.access_token == '') {
          this.api.login()
        }
      },
      fail: () => {
        this.api.login()
      }
    })
  },
  globalData: {
    request_ret: {
      SUCCESS: 0,
      FAILURE: -1,
      ACCESS_TOKEN_REFRESHED: 1000,
      ACCESS_TOKEN_INVALID: 1001
    },
    api_url: 'https://diandi.samler.cn/api/',
    // api_url: 'http://localhost:8081/api/',
    userInfo: null,
    access_token: wx.getStorageSync('access_token'),
    position_inited: false,
    position: {
      lat: 24.625308990478516,
      lng: 118.08626556396484
    },
    lbs: {
      key: 'SX2BZ-5CNCG-NHIQT-IEYJK-RNHEJ-OXBR2'
    }
  },
  api: {
    login: (callback) => {
      wx.showLoading({
        mask: true,
        title: '请稍候',
      })
      
      wx.login({
        success: res => {
          const ins = getApp()
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          ins.api.requestApi('user/login', 'POST', {
              type: 'wechat_mini_program',
              code: res.code
            },
            {
              complete: () => {
                wx.hideLoading({
                  success: (res) => {},
                })
              },
              success: (resp) => {
                let data = resp.data
                
                if(data.ret == ins.globalData.request_ret.SUCCESS) {
                  ins.globalData.access_token = data.data.access_token
                  wx.setStorageSync('access_token', data.data.access_token)

                  if(callback != undefined &&callback != null) {
                    console.log("重新登录后 重发请求")
                    callback()
                  }
                }
              }
            }
          )
        }
      })
    },
    requestApi: (path, method, data, callback, loading) => {
      const ins = getApp();
      if(loading) {
        wx.showLoading({
          title: '请稍候',
        })
      }

      wx.request({
        url: ins.globalData.api_url + path,
        method: method,
        header: {
          'access_token': ins.globalData.access_token
        },
        data: data,
        complete: (resp) => {
          if(loading) {
            wx.hideLoading()
          }

          if(callback != null && typeof callback.complete == "function") {
            callback.complete(resp)
          }
        },
        success: (resp) => {
          if(resp.data.ret == ins.globalData.request_ret.ACCESS_TOKEN_REFRESHED) {
            ins.globalData.access_token = resp.data.data.access_token
            wx.setStorageSync('access_token', data.data.access_token)

            ins.api.requestApi(path, method, data, callback, loading)
          }
          else if(resp.data.ret == ins.globalData.request_ret.ACCESS_TOKEN_INVALID) {
            ins.api.login(() => {
              ins.api.requestApi(path, method, data, callback, loading)
            })
          }
          else {
            if(callback != null && typeof callback.success == "function") {
              callback.success(resp)
            }
          }
        },
        fail: resp => {
          if(callback != null && typeof callback.complete == "function") {
            callback.fail(resp)
          }
        }
      })
    },
    upload(filePath, data, callback, loading) {
      const ins = getApp();
      if(loading) {
        wx.showLoading({title: '请稍候', mask: true})
      }

      wx.uploadFile({
        url: ins.globalData.api_url + 'file/upload',
        header: {
          'access_token': ins.globalData.access_token
        },
        filePath: filePath,
        name: 'file',
        formData: data,
        complete: resp => {
          if(loading) {
            wx.hideLoading()
          }

          if(callback != null && typeof callback.complete == "function") {
            callback.complete(resp)
          }
        },
        success: resp => {
          resp.data = JSON.parse(resp.data)
          if(resp.data.ret == ins.globalData.request_ret.ACCESS_TOKEN_REFRESHED) {
            ins.globalData.access_token = resp.data.data.access_token
            wx.setStorageSync('access_token', data.data.access_token)

            ins.api.upload(filePath, data, callback, loading)
          }
          else if(resp.data.ret == ins.globalData.request_ret.ACCESS_TOKEN_INVALID) {
            ins.api.login(() => {
              ins.api.upload(filePath, data, callback, loading)
            })
          }
          else {
            if(callback != null && typeof callback.success == "function") {
              callback.success(resp)
            }
          }
        },
        fail: resp => {
          if(callback != null && typeof callback.fail == "function") {
            callback.fail(resp)
          }
        }
      })
    }
  }
})

